<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户设置
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-select v-model="query.fieldName" placeholder="类型" class="handle-select mr10">
                    <el-option key="1" label="所有类型" value=""></el-option>
                    <el-option key="2" label="员工工号" value="knumber"></el-option>
                    <el-option key="3" label="员工姓名" value="username"></el-option>
                </el-select>
                <el-input
                    v-model="query.keyWord"
                    placeholder="工号/用户名关键字搜索"
                    class="handle-input mr10"
                ></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <div style=" width: 60%;float: right;">
                    <div style="width:50%;float:left">
                        <el-alert
                            title="新增的数据第一次默认显示在第一条方便比对"
                            type="success"
                            :center="true"
                            :closable="false">
                        </el-alert>
                    </div>
                    <!-- 时间按钮 -->
                   <div style="width:49%;float:right;">
                        <el-button style="float:right;"
                            type="success"
                            class="mr10"
                            icon="el-icon-plus"
                            @click="handleAdd"
                            align="right"
                        >添加</el-button>
                   </div>
                </div>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                :row-style="rowStyle"
            >
                <el-table-column prop="id" label="员工ID" width="100" align="center"></el-table-column>
                <el-table-column prop="kNumber" label="员工工号" align="center"></el-table-column>
                <el-table-column prop="userName" label="员工姓名" align="center"></el-table-column>
                <el-table-column prop="pwd" label="密码" align="center">
                    <template slot-scope="scope">
                        <span
                            v-if="scope.row.isShowPassWord"
                             class="show"
                            @click="showpass(scope.row)"
                        >{{scope.row.pwd}}</span>
                        <span v-else class="show" @click="showpass(scope.row)">******</span>
                    </template>
                </el-table-column>
                <el-table-column prop="email" label="Email" align="center"></el-table-column>
                <el-table-column prop="tel" label="电话" align="center"></el-table-column>
                <el-table-column prop="createTime" label="注册时间" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.createTime | dateFormat }}
                    </template>
                </el-table-column>
                <el-table-column prop="isDelete" label="是否删除" align="center">
                    <template slot-scope="scope">{{scope.row.isDelete?"是":"否"}}</template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    :pager-count="pagerCount"
                    :page-sizes="pageSizes"
                    :hide-on-single-page="false"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 添加弹出框 -->
        <el-dialog
            title="员工编辑"
            :visible.sync="editVisible"
            width="30%"
            :close-on-press-escape="false"
        >
            <el-form ref="form_user" :rules="rules" :model="form" label-width="70px">
                <el-form-item v-if="isShowId" label="员工Id" label-width="120px">
                    <el-input v-model="form.id" readonly></el-input>
                </el-form-item>
                <el-form-item label-width="120px" prop="kNumber" label="员工工号">
                    <el-input v-model="form.kNumber"></el-input>
                </el-form-item>
                <el-form-item label-width="120px" prop="userName" label="员工姓名">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label-width="120px" prop="email" label="员工邮箱">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label-width="120px" prop="tel" label="员工电话">
                    <el-input v-model="form.tel"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveInfo('form_user')">确 定</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'basetable',
    data() {
        //检测邮箱格式
        var checkEmail = (rule, value, callback) => {
            const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
            if (!value) {
                return callback(new Error('邮箱不能为空'));
            }
            setTimeout(() => {
                if (mailReg.test(value)) {
                    callback();
                } else {
                    callback(new Error('请输入正确的邮箱格式'));
                }
            }, 100);
        };
        var checkKNumber = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('员工编号不能为空'));
            }

            //表示为更新,更新就直接通过
            if(this.isShowId){
                return callback();
            }
            //是添加才判断是否重名
            setTimeout(() => {
                this.$http({
                        url: 'http://localhost:5001/UserInfo/FindKNumber',
                        method: 'get',
                        params: {
                            KNumber: value
                        }
                }).then(res => {
                    this.$log(res);
                    if (res.state == 300) return callback(new Error(res.data));
                    else {
                        callback();
                    }
                });
                
            }, 100);
        };
        return {
            //查询字段
            query: {
                //username和knumber2个字段
                fieldName: '',
                keyWord: '',
                pageIndex: 1,
                pageSize: 11
            },
            tableData: [],
            delList: [],
            editVisible: false, //编辑窗体是否显示
            //显示几个页码其它的是...代替,并且只能设置的范围在5-21之间的奇数，否则会报错
            pagerCount: 7,
            pageSizes: [10, 20, 30, 40, 50, 100],
            pageTotal: 0,
            form: {}, //提交数据
            //判断添加时不显示id的选项
            isShowId: false,
            //对应form表单的:rules属性
            rules: {
                //knumber对应el-form-item的prop属性名称以及form中的属性要一一对应，3者名称必须要一致,
                kNumber: [
                    { required: true, message: '请输入工号', trigger: 'blur' },
                    { validator: checkKNumber, trigger: 'blur' }
                ],
                userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                //validator验证的方法名称，这个方法必须要比return前面，否则加载不到了
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                tel: [{ required: true, message: '请输入电话', trigger: 'blur' }]
            }
        };
    },
    created() {
        this.getData();
    },
    methods: {
        //显示和隐藏密码
        showpass(row) {
            this.$set(row, 'isShowPassWord', !row.isShowPassWord);
        },
        //显示添加窗体
        handleAdd() {
            //临时数据添加
            let addAdminData = {
                kNumber: 'admin',
                userName: '超级管理员',
                email: 'admin@qq.com',
                tel: '13888888888'
            };
            this.form = addAdminData;
            this.isShowId = false; //添加的时候需要隐藏id输入框
            this.editVisible = true; //显示编辑窗体
        },
        // 保存编辑
        saveInfo(fromname) {
            this.$refs[fromname].validate(valid => {
                if (!valid) {
                    return false;
                } 
                this.$log(this.isShowId)
                //表示为更新
                if(this.isShowId){
                    this.updateUser();
                }
                //表示添加
                else{
                    this.addUser();
                }
                
            });
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            //临时数据
            this.$http({
                url: '/UserInfo/Index?time='+new Date().getSeconds(),
                method: 'get',
                params: this.query
            }).then(res => {
                this.tableData = res.data.result;
                this.pageTotal = res.data.pageTotal;
            });
        },
        // 触发搜索按钮
        handleSearch() {
            //查询时从第一页开始
            this.query.pageIndex = 1;
            if(this.query.keyWord != "" && this.query.fieldName == ""){
                this.$message.error('请选择查询类型...');
                return;
            }

            this.getData();
        },
        // 当前页事件
        handlePageChange(crrentPageIndex) {
            this.query.pageIndex = crrentPageIndex;
            this.getData();
        },
        // 编辑操作
        handleEdit(index, row) {
            this.isShowId = true; //显示id栏
            this.form = row;
            this.editVisible = true;
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                this.$http({
                    url: '/UserInfo/DeleteUserInfo',
                    method: 'post',
                    params: {
                        userId: row.id
                    }
                }).then(res => {
                    if (res.state == 500) {
                        this.$message.success(`删除失败`);
                    } else {
                        this.$message.success(`删除成功`);
                        //将对应的索引数据删除并且插入伪深处之后的
                        // this.tableData.splice(index, 1,res.data);
                        this.tableData[index].isDelete = true;
                    }
                });
                
            })
            .catch(() => {});
        },
        //添加用户
        addUser(){
            this.$http({
                    url: '/UserInfo/AddUserInfo',
                    method: 'post',
                    params: this.form
                }).then(res => {
                    if (res.state == 300) {
                        //表示后台验证错误
                        let message = '';
                        for (var key in res.data) {
                            message += " <span style='color:red;'>" + res.data[key] + '</span><br/>';
                        }
                        this.$notify.error({
                            title: '后台验证未通过',
                            dangerouslyUseHTMLString: true,
                            message: message
                        });
                    } else {
                        this.editVisible = false; //关闭编辑窗体
                        this.$message.success(`保存成功`);
                        //临时将添加的数据放在第一排
                        this.tableData.unshift(res.data);
                    }
                });
        },
        //修改用户数据
        updateUser(){
            this.$http({
                    url: '/UserInfo/UpdateUserInfo',
                    method: 'post',
                    params: this.form
                }).then(res => {
                    if (res.state == 300 || res.state == 500) {
                        //表示后台验证错误
                        let message = '';
                        for (var key in res.data) {
                            message += " <span style='color:red;'>" + res.data[key] + '</span><br/>';
                        }
                        this.$notify.error({
                            title: '后台验证未通过',
                            dangerouslyUseHTMLString: true,
                            message: message
                        });
                    } else {
                        this.editVisible = false; //关闭编辑窗体
                        this.$message.success(`保存成功`);
                    }
                });
        },
        //绑定行的事件样式（其实就是改变了table中的数据tableData就会触发此事件）
        rowStyle({ row, rowIndex}){
            if(row.isDelete == true){
                this.$log(row)
                 return {
                    "color": "red"
                    };
            }
        },
        bb(){
            this.$log("测试看看能不能合并到aa方法");
            //看看第二次是否能成功
            //第三次看看能否成功
            //123456789
            this.$log("这句代码多了一点东西");
            //暂时测试成功,测试一波免密码
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.btn-prev:before {
    content: '上一页';
}
.btn-next:before {
    content: '下一页';
}
.show {
    cursor: pointer;
}
.right-float{
    width: 60%;
    float: right;
}
</style>
